//
//  SnowView.m
//  Snow
//
//  Created by 吕飞俊 on 16/2/29.
//  Copyright © 2016年 zhiyou. All rights reserved.
//

#import "SnowView.h"

@interface SnowView()

@property(nonatomic, strong) NSMutableArray *imgArray;
@property(nonatomic, assign) NSTimeInterval animationDuration;

@end

@implementation SnowView

- (instancetype)initWithFrame:(CGRect)frame
            animationDuration:(NSTimeInterval)animationDuration
              backgroundColor:(UIColor *)backgroundColor
                 timeInterval:(NSTimeInterval)timeInterval{
    
    self = [super initWithFrame:frame];
    if (self) {
        self.animationDuration = animationDuration;
        self.backgroundColor = backgroundColor;
        self.imgArray = [[NSMutableArray alloc]initWithCapacity:0];
        [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    }
    return self;
}

-(void)onTimer{
    UIImageView *snow=nil;
    if (self.imgArray.count>0) {
        //取雪花
        snow=[self.imgArray firstObject];
        [self.imgArray removeObject:snow];
    }else{
        //创建雪花
        snow=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"snow"]];
//        snow=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"RMB"]];
        snow.backgroundColor = [UIColor clearColor];
        [self addSubview:snow];
    }
    snow.frame = CGRectMake(arc4random()%((NSInteger)self.frame.size.width-50+1), -50, 50, 50);
//    snow.frame = CGRectMake(arc4random()%((NSInteger)self.frame.size.width-100+1), -50, 100, 50);
    [UIView beginAnimations:nil context:(__bridge void * _Nullable)(snow)];
    [UIView setAnimationDuration:self.animationDuration];
    snow.frame = CGRectMake(arc4random()%((NSInteger)self.frame.size.width-50+1), self.frame.size.height, 50, 50);
//    snow.frame = CGRectMake(arc4random()%((NSInteger)self.frame.size.width-100+1), self.frame.size.height, 100, 50);
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
    [UIView commitAnimations];
}

-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
    UIImageView *snow=(__bridge UIImageView *)context;
    [self.imgArray addObject:snow];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
